package com.example.myapplication;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.usage.UsageStatsManager;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * 应用使用统计Activity
 */
public class AppUsageActivity extends AppCompatActivity {
    private AppUsageService appUsageService;
    private AppUsageAdapter appUsageAdapter;
    private RecyclerView recyclerAppUsage;
    private LinearLayout layoutEmpty;
    private TextView textPermissionStatus;
    private TextView textTimeRange;
    private Button btnDaily;
    private Button btnWeekly;
    private Button btnMonthly;
    private Button btnYearly;
    private Button btnBest;
    private Button btnCustomDate;
    private Button btnUpload;
    
    private int currentIntervalType = UsageStatsManager.INTERVAL_DAILY; // 当前选中的间隔类型
    private long customStartTime = 0;
    private long customEndTime = 0;
    
    private AlertDialog permissionDialog; // 保存权限请求对话框的引用
    private boolean hasShownPermissionDialog = false;
    
    private AppUsageUploadService appUsageUploadService; // 上报服务

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_app_usage);

        initViews();
        initServices();
        setupClickListeners();
        checkPermissionAndLoadData();
    }

    private void initViews() {
        recyclerAppUsage = findViewById(R.id.recycler_app_usage);
        layoutEmpty = findViewById(R.id.layout_empty);
        textPermissionStatus = findViewById(R.id.text_permission_status);
        textTimeRange = findViewById(R.id.text_time_range);
        btnDaily = findViewById(R.id.btn_daily);
        btnWeekly = findViewById(R.id.btn_weekly);
        btnMonthly = findViewById(R.id.btn_monthly);
        btnYearly = findViewById(R.id.btn_yearly);
        btnBest = findViewById(R.id.btn_best);
        btnCustomDate = findViewById(R.id.btn_custom_date);
        btnUpload = findViewById(R.id.btn_upload);
        
        // 设置权限状态文本点击事件
        textPermissionStatus.setOnClickListener(v -> {
            if (!appUsageService.hasUsageStatsPermission()) {
                requestUsageStatsPermission();
            }
        });

        // 设置RecyclerView
        recyclerAppUsage.setLayoutManager(new LinearLayoutManager(this));
        appUsageAdapter = new AppUsageAdapter(this, null);
        recyclerAppUsage.setAdapter(appUsageAdapter);
    }

    private void initServices() {
        appUsageService = new AppUsageService(this);
        appUsageUploadService = new AppUsageUploadService(this);
    }

    private void setupClickListeners() {
        // 间隔类型切换
        btnDaily.setOnClickListener(v -> {
            currentIntervalType = UsageStatsManager.INTERVAL_DAILY;
            customStartTime = 0;
            customEndTime = 0;
            updateTabSelection();
            loadAppUsageData();
        });

        btnWeekly.setOnClickListener(v -> {
            currentIntervalType = UsageStatsManager.INTERVAL_WEEKLY;
            customStartTime = 0;
            customEndTime = 0;
            updateTabSelection();
            loadAppUsageData();
        });
        
        btnMonthly.setOnClickListener(v -> {
            currentIntervalType = UsageStatsManager.INTERVAL_MONTHLY;
            customStartTime = 0;
            customEndTime = 0;
            updateTabSelection();
            loadAppUsageData();
        });
        
        btnYearly.setOnClickListener(v -> {
            currentIntervalType = UsageStatsManager.INTERVAL_YEARLY;
            customStartTime = 0;
            customEndTime = 0;
            updateTabSelection();
            loadAppUsageData();
        });
        
        btnBest.setOnClickListener(v -> {
            currentIntervalType = UsageStatsManager.INTERVAL_BEST;
            customStartTime = 0;
            customEndTime = 0;
            updateTabSelection();
            loadAppUsageData();
        });

        btnCustomDate.setOnClickListener(v -> {
            showDateRangePicker();
        });
        
        // 上报数据按钮
        btnUpload.setOnClickListener(v -> {
            uploadAppUsageData();
        });

        // 权限状态点击
        textPermissionStatus.setOnClickListener(v -> {
            if (!appUsageService.hasUsageStatsPermission()) {
                requestUsageStatsPermission();
            } else {
                Toast.makeText(this, "权限已授权", Toast.LENGTH_SHORT).show();
            }
        });

        // 应用项点击
        appUsageAdapter.setOnItemClickListener(appUsageInfo -> {
            Toast.makeText(this, "点击了: " + appUsageInfo.getAppName(), Toast.LENGTH_SHORT).show();
            // 这里可以跳转到应用详情页面
        });
    }

    private void updateTabSelection() {
        btnDaily.setSelected(currentIntervalType == UsageStatsManager.INTERVAL_DAILY && customStartTime == 0);
        btnWeekly.setSelected(currentIntervalType == UsageStatsManager.INTERVAL_WEEKLY && customStartTime == 0);
        btnMonthly.setSelected(currentIntervalType == UsageStatsManager.INTERVAL_MONTHLY && customStartTime == 0);
        btnYearly.setSelected(currentIntervalType == UsageStatsManager.INTERVAL_YEARLY && customStartTime == 0);
        btnBest.setSelected(currentIntervalType == UsageStatsManager.INTERVAL_BEST && customStartTime == 0);
        btnCustomDate.setSelected(customStartTime > 0 && customEndTime > 0);
        updateTimeRangeDisplay();
    }
    
    /**
     * 更新时间范围显示
     */
    private void updateTimeRangeDisplay() {
        if (customStartTime > 0 && customEndTime > 0) {
            // 自定义日期范围
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
            String startDateStr = sdf.format(new Date(customStartTime));
            String endDateStr = sdf.format(new Date(customEndTime));
            textTimeRange.setText(startDateStr + " 至 " + endDateStr + " 使用统计");
        } else {
            // 根据间隔类型显示
            String intervalName = getIntervalTypeName(currentIntervalType);
            textTimeRange.setText(intervalName + "使用统计");
        }
    }
    
    /**
     * 获取间隔类型名称
     */
    private String getIntervalTypeName(int intervalType) {
        switch (intervalType) {
            case UsageStatsManager.INTERVAL_DAILY:
                return "今日";
            case UsageStatsManager.INTERVAL_WEEKLY:
                return "本周";
            case UsageStatsManager.INTERVAL_MONTHLY:
                return "本月";
            case UsageStatsManager.INTERVAL_YEARLY:
                return "今年";
            case UsageStatsManager.INTERVAL_BEST:
                return "最佳间隔";
            default:
                return "未知";
        }
    }
    
    /**
     * 显示日期范围选择器
     */
    private void showDateRangePicker() {
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        
        DatePickerDialog startDatePicker = new DatePickerDialog(this, (view, selectedYear, selectedMonth, selectedDay) -> {
            Calendar startCal = Calendar.getInstance();
            startCal.set(selectedYear, selectedMonth, selectedDay, 0, 0, 0);
            customStartTime = startCal.getTimeInMillis();
            
            // 选择结束日期
            showEndDatePicker();
        }, year, month, day);
        
        startDatePicker.setTitle("选择开始日期");
        startDatePicker.show();
    }
    
    /**
     * 显示结束日期选择器
     */
    private void showEndDatePicker() {
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        
        DatePickerDialog endDatePicker = new DatePickerDialog(this, (view, selectedYear, selectedMonth, selectedDay) -> {
            Calendar endCal = Calendar.getInstance();
            endCal.set(selectedYear, selectedMonth, selectedDay, 23, 59, 59);
            customEndTime = endCal.getTimeInMillis();
            
            // 验证日期范围
            if (customEndTime <= customStartTime) {
                Toast.makeText(this, "结束日期必须晚于开始日期", Toast.LENGTH_SHORT).show();
                return;
            }
            
            // 更新UI并加载数据
            updateTabSelection();
            loadCustomDateData();
            
            // 显示选择的日期范围
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
            String startDateStr = sdf.format(new Date(customStartTime));
            String endDateStr = sdf.format(new Date(customEndTime));
            Toast.makeText(this, "已选择: " + startDateStr + " 至 " + endDateStr, Toast.LENGTH_LONG).show();
        }, year, month, day);
        
        endDatePicker.setTitle("选择结束日期");
        endDatePicker.show();
    }
    
    /**
     * 加载自定义日期范围的数据
     */
    private void loadCustomDateData() {
        if (!appUsageService.hasUsageStatsPermission()) {
            showEmptyState();
            return;
        }

        try {
            List<AppUsageInfo> appUsageList = appUsageService.getAppUsageByDateRange(customStartTime, customEndTime);
            
            if (appUsageList.isEmpty()) {
                showEmptyState();
            } else {
                appUsageAdapter.updateData(appUsageList);
                showAppList();
            }
        } catch (Exception e) {
            Toast.makeText(this, "加载数据失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
            showEmptyState();
        }
    }

    private void checkPermissionAndLoadData() {
        boolean hasPermission = appUsageService.hasUsageStatsPermission();
        
        android.util.Log.d("AppUsageActivity", "权限检查结果: " + hasPermission);
        
        if (hasPermission) {
            // 如果权限已授权，关闭对话框（如果存在）
            dismissPermissionDialog();
            
            textPermissionStatus.setText("已授权");
            textPermissionStatus.setBackgroundColor(getResources().getColor(android.R.color.holo_green_light));
            loadAppUsageData();
        } else {
            textPermissionStatus.setText("未授权 - 点击授权");
            textPermissionStatus.setBackgroundColor(getResources().getColor(android.R.color.holo_red_light));
            showEmptyState();
            
            // 显示详细的权限请求提示（仅在首次检查时显示，避免重复弹出）
            if (!hasShownPermissionDialog) {
                showPermissionRequestDialog();
                hasShownPermissionDialog = true;
            }
        }
    }
    
    /**
     * 关闭权限请求对话框
     */
    private void dismissPermissionDialog() {
        if (permissionDialog != null && permissionDialog.isShowing()) {
            permissionDialog.dismiss();
            permissionDialog = null;
            android.util.Log.d("AppUsageActivity", "权限对话框已关闭");
        }
    }
    
    /**
     * 显示权限请求对话框
     */
    private void showPermissionRequestDialog() {
        // 如果已有对话框在显示，先关闭它
        dismissPermissionDialog();
        
        permissionDialog = new AlertDialog.Builder(this)
                .setTitle("需要使用统计权限")
                .setMessage("应用使用统计功能需要\"使用情况访问权限\"才能正常工作。\n\n" +
                           "请按以下步骤授权：\n" +
                           "1. 点击\"去设置\"按钮\n" +
                           "2. 在设置页面找到本应用\n" +
                           "3. 开启\"使用情况访问权限\"\n" +
                           "4. 返回应用即可使用")
                .setPositiveButton("去设置", (dialog, which) -> {
                    requestUsageStatsPermission();
                })
                .setNegativeButton("取消", (dialog, which) -> {
                    permissionDialog = null;
                })
                .setCancelable(false)
                .setOnDismissListener(dialog -> {
                    permissionDialog = null;
                })
                .create();
        
        permissionDialog.show();
    }

    private void loadAppUsageData() {
        if (!appUsageService.hasUsageStatsPermission()) {
            showEmptyState();
            return;
        }

        try {
            List<AppUsageInfo> appUsageList;
            
            if (customStartTime > 0 && customEndTime > 0) {
                // 自定义日期范围
                appUsageList = appUsageService.getAppUsageByDateRange(customStartTime, customEndTime);
            } else {
                // 使用间隔类型
                appUsageList = appUsageService.getAppUsageByInterval(currentIntervalType);
            }

            if (appUsageList != null && !appUsageList.isEmpty()) {
                appUsageAdapter.updateData(appUsageList);
                showAppList();
                // 打印排行榜数据
                printAppUsageRanking(appUsageList);
            } else {
                showEmptyState();
            }
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, "加载数据失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
            showEmptyState();
        }
    }
    
    /**
     * 打印应用使用排行榜数据
     */
    private void printAppUsageRanking(List<AppUsageInfo> appUsageList) {
        if (appUsageList == null || appUsageList.isEmpty()) {
            android.util.Log.d("AppUsageRanking", "排行榜数据为空");
            return;
        }
        
        // 计算总使用时间
        long totalUsageTime = 0;
        for (AppUsageInfo appUsageInfo : appUsageList) {
            totalUsageTime += appUsageInfo.getTotalTimeInForeground();
        }
        
        // 获取间隔类型名称
        String intervalName = getIntervalTypeName(currentIntervalType);
        if (customStartTime > 0 && customEndTime > 0) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
            intervalName = sdf.format(new Date(customStartTime)) + " 至 " + sdf.format(new Date(customEndTime));
        }
        
        // 打印标题
        android.util.Log.d("AppUsageRanking", "==========================================");
        android.util.Log.d("AppUsageRanking", "应用使用排行榜 - " + intervalName);
        android.util.Log.d("AppUsageRanking", "总应用数: " + appUsageList.size());
        android.util.Log.d("AppUsageRanking", "总使用时间: " + formatTime(totalUsageTime));
        android.util.Log.d("AppUsageRanking", "==========================================");
        android.util.Log.d("AppUsageRanking", String.format("%-5s | %-30s | %-15s | %-10s | %-20s", 
                "排名", "应用名称", "使用时间", "百分比", "包名"));
        android.util.Log.d("AppUsageRanking", "------------------------------------------");
        
        // 打印排行榜数据
        for (int i = 0; i < appUsageList.size(); i++) {
            AppUsageInfo appUsageInfo = appUsageList.get(i);
            int rank = i + 1;
            String appName = appUsageInfo.getAppName();
            String packageName = appUsageInfo.getPackageName();
            long usageTime = appUsageInfo.getTotalTimeInForeground();
            String formattedTime = appUsageInfo.getFormattedTime();
            float percentage = totalUsageTime > 0 ? 
                    (float) usageTime / totalUsageTime * 100 : 0;
            
            // 限制应用名称长度
            if (appName.length() > 28) {
                appName = appName.substring(0, 25) + "...";
            }
            
            // 限制包名长度
            if (packageName.length() > 18) {
                packageName = packageName.substring(0, 15) + "...";
            }
            
            android.util.Log.d("AppUsageRanking", String.format("%-5d | %-30s | %-15s | %-9.2f%% | %-20s",
                    rank, appName, formattedTime, percentage, packageName));
            
            // 前10名单独打印详细信息
            if (rank <= 10) {
                android.util.Log.d("AppUsageRanking", String.format(
                        "  [%d] %s\n    包名: %s\n    使用时间: %s (%,d 毫秒)\n    占比: %.2f%%\n    最后使用: %s",
                        rank, appUsageInfo.getAppName(), 
                        appUsageInfo.getPackageName(),
                        formattedTime, usageTime,
                        percentage,
                        appUsageInfo.getLastTimeUsed() > 0 ? 
                                new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
                                        .format(new Date(appUsageInfo.getLastTimeUsed())) : "未知"));
            }
        }
        
        android.util.Log.d("AppUsageRanking", "==========================================");
        
        // 打印JSON格式（用于调试）
        printAppUsageRankingJson(appUsageList, intervalName, totalUsageTime);
    }
    
    /**
     * 打印应用使用排行榜数据（JSON格式）
     */
    private void printAppUsageRankingJson(List<AppUsageInfo> appUsageList, String intervalName, long totalUsageTime) {
        try {
            StringBuilder jsonBuilder = new StringBuilder();
            jsonBuilder.append("{\n");
            jsonBuilder.append("  \"interval\": \"").append(intervalName).append("\",\n");
            jsonBuilder.append("  \"totalCount\": ").append(appUsageList.size()).append(",\n");
            jsonBuilder.append("  \"totalUsageTime\": ").append(totalUsageTime).append(",\n");
            jsonBuilder.append("  \"totalUsageTimeFormatted\": \"").append(formatTime(totalUsageTime)).append("\",\n");
            jsonBuilder.append("  \"ranking\": [\n");
            
            for (int i = 0; i < appUsageList.size(); i++) {
                AppUsageInfo appUsageInfo = appUsageList.get(i);
                jsonBuilder.append("    {\n");
                jsonBuilder.append("      \"rank\": ").append(i + 1).append(",\n");
                jsonBuilder.append("      \"appName\": \"").append(escapeJson(appUsageInfo.getAppName())).append("\",\n");
                jsonBuilder.append("      \"packageName\": \"").append(escapeJson(appUsageInfo.getPackageName())).append("\",\n");
                jsonBuilder.append("      \"usageTime\": ").append(appUsageInfo.getTotalTimeInForeground()).append(",\n");
                jsonBuilder.append("      \"usageTimeFormatted\": \"").append(appUsageInfo.getFormattedTime()).append("\",\n");
                float percentage = totalUsageTime > 0 ? 
                        (float) appUsageInfo.getTotalTimeInForeground() / totalUsageTime * 100 : 0;
                jsonBuilder.append("      \"percentage\": ").append(String.format("%.2f", percentage)).append(",\n");
                jsonBuilder.append("      \"lastTimeUsed\": ").append(appUsageInfo.getLastTimeUsed()).append(",\n");
                if (appUsageInfo.getLastTimeUsed() > 0) {
                    jsonBuilder.append("      \"lastTimeUsedFormatted\": \"").append(
                            new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
                                    .format(new Date(appUsageInfo.getLastTimeUsed()))).append("\",\n");
                }
                jsonBuilder.append("      \"launchCount\": ").append(appUsageInfo.getLaunchCount()).append("\n");
                jsonBuilder.append("    }");
                if (i < appUsageList.size() - 1) {
                    jsonBuilder.append(",");
                }
                jsonBuilder.append("\n");
            }
            
            jsonBuilder.append("  ]\n");
            jsonBuilder.append("}");
            
            android.util.Log.d("AppUsageRanking", "JSON格式数据:");
            android.util.Log.d("AppUsageRanking", jsonBuilder.toString());
        } catch (Exception e) {
            android.util.Log.e("AppUsageRanking", "打印JSON格式失败", e);
        }
    }
    
    /**
     * 格式化时间（毫秒转可读格式）
     */
    private String formatTime(long milliseconds) {
        long totalSeconds = milliseconds / 1000;
        long hours = totalSeconds / 3600;
        long minutes = (totalSeconds % 3600) / 60;
        long seconds = totalSeconds % 60;
        
        if (hours > 0) {
            return String.format("%d小时%d分钟%d秒", hours, minutes, seconds);
        } else if (minutes > 0) {
            return String.format("%d分钟%d秒", minutes, seconds);
        } else {
            return String.format("%d秒", seconds);
        }
    }
    
    /**
     * JSON转义字符串
     */
    private String escapeJson(String str) {
        if (str == null) return "";
        return str.replace("\\", "\\\\")
                  .replace("\"", "\\\"")
                  .replace("\n", "\\n")
                  .replace("\r", "\\r")
                  .replace("\t", "\\t");
    }
    
    /**
     * 上报应用使用统计数据
     */
    private void uploadAppUsageData() {
        if (!appUsageService.hasUsageStatsPermission()) {
            Toast.makeText(this, "没有使用统计权限，无法上报数据", Toast.LENGTH_SHORT).show();
            return;
        }
        
        // 确定要上报的间隔类型
        int intervalType = currentIntervalType;
        if (customStartTime > 0 && customEndTime > 0) {
            // 自定义日期范围，使用 INTERVAL_BEST
            intervalType = UsageStatsManager.INTERVAL_BEST;
            Toast.makeText(this, "自定义日期范围将使用最佳间隔上报", Toast.LENGTH_SHORT).show();
        }
        
        // 显示上传提示
        Toast.makeText(this, "正在上报数据...", Toast.LENGTH_SHORT).show();
        btnUpload.setEnabled(false);
        btnUpload.setText("上报中...");
        
        // 上报数据
        appUsageUploadService.uploadAppUsageData(intervalType, new DeviceDataUploader.UploadCallback() {
            @Override
            public void onSuccess(String response) {
                runOnUiThread(() -> {
                    btnUpload.setEnabled(true);
                    btnUpload.setText("上报数据");
                    Toast.makeText(AppUsageActivity.this, "数据上报成功！", Toast.LENGTH_SHORT).show();
                    android.util.Log.d("AppUsageActivity", "上报成功: " + response);
                });
            }
            
            @Override
            public void onError(String error) {
                runOnUiThread(() -> {
                    btnUpload.setEnabled(true);
                    btnUpload.setText("上报数据");
                    Toast.makeText(AppUsageActivity.this, "数据上报失败: " + error, Toast.LENGTH_SHORT).show();
                    android.util.Log.e("AppUsageActivity", "上报失败: " + error);
                });
            }
        });
    }

    private void showAppList() {
        recyclerAppUsage.setVisibility(View.VISIBLE);
        layoutEmpty.setVisibility(View.GONE);
    }

    private void showEmptyState() {
        recyclerAppUsage.setVisibility(View.GONE);
        layoutEmpty.setVisibility(View.VISIBLE);
    }

    private void requestUsageStatsPermission() {
        try {
            Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
            startActivity(intent);
            Toast.makeText(this, "请在设置中找到本应用并开启\"使用情况访问权限\"", Toast.LENGTH_LONG).show();
        } catch (Exception e) {
            Toast.makeText(this, "无法打开设置页面: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 从设置页面返回时重新检查权限
        // 检查权限状态，如果已授权会自动关闭对话框
        boolean hadDialog = (permissionDialog != null && permissionDialog.isShowing());
        checkPermissionAndLoadData();
        
        // 如果之前有对话框显示，但现在权限已授权，说明用户成功授权了
        if (hadDialog && appUsageService.hasUsageStatsPermission()) {
            android.util.Log.d("AppUsageActivity", "用户已从设置页面授权成功，对话框已自动关闭");
            Toast.makeText(this, "权限授权成功！", Toast.LENGTH_SHORT).show();
        }
        
        // 重置对话框标志，允许再次显示（如果用户从设置返回但未授权）
        hasShownPermissionDialog = false;
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
        // Activity销毁时关闭对话框，避免内存泄漏
        dismissPermissionDialog();
    }
}
